﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace NetFramework
{
    class StateObjPool : IClientPool
    {
        public static StateObjPool Instance = new StateObjPool(defaultClientNum);
        private Dictionary<bool, StateObject> _lstStateObj = new Dictionary<bool, StateObject>();
        private object lockObj = new object();
        private const int defaultClientNum = 10;

        private StateObjPool(int num)
        {
            if (num <= 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            for (int i = 0; i < num; i++)
            {
                _lstStateObj.Add(true, new StateObject(2048, new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)));
            }
        }

        public StateObject GetIdelClient()
        {
            lock (_lstStateObj)
            {
                foreach (var clientObj in _lstStateObj)
                {
                    if (clientObj.Key)
                    {
                        return clientObj.Value;
                    }
                }
                StateObject client = new StateObject(2048, new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));
                _lstStateObj.Add(true, client);
                
                return client;
            }
        }

        public void ReleaseWorkClient(StateObject client)
        {
            lock (_lstStateObj)
            {
                foreach (var clientObj in _lstStateObj)
                {
                    //if (clientObj.Value)
                    //{
                        
                    //}
                }
            }
        }
    }
}
